<script setup lang="ts">
import { ref } from 'vue'
import {showNotify} from 'vant'
import { Print } from '@/api/Base/printer'

interface PrintContent {
  label: {
    label_type: string
    printer: string
    tape: string
    fontname: string
    size: string
    align: string
    qrtext: string
    lines: string[]
  }
  count: number
}

const props = defineProps<{
  printContent?: PrintContent
}>()

const showPopup = ref(false)
const quantity = ref(1)
const printProgress = ref(0)
const isPrinting = ref(false)

const show = () => {
  showPopup.value = true
}

const print = async () => {
  isPrinting.value = true
  printProgress.value = 0

  try {
    // Simulate progress
    const interval = setInterval(() => {
      printProgress.value += 10
      if (printProgress.value >= 100) {
        clearInterval(interval)
      }
    }, 300)

    await Print({
      label: props.printContent?.label || {
        label_type: "qr",
        printer: "office",
        tape: "9mm",
        fontname: "mono",
        size: "small",
        align: "right",
        qrtext: "Y240121222",
        lines: ["Y240121222"]
      },
      count: quantity.value
    })

    clearInterval(interval)
    printProgress.value = 100
    showNotify({ type: 'success', message: '打印成功' })
    showPopup.value = false
  } catch (error) {
    showNotify({ type: 'danger', message: '打印失败' })
  } finally {
    isPrinting.value = false
  }
}

defineExpose({
  show
})
</script>

<template>
  <van-popup v-model:show="showPopup" position="bottom" round class="h-[50vh] flex flex-col">
    <div class="flex-1 p-4">
      <div class="flex flex-col gap-4 p-4">
        <div class="flex items-center justify-between bg-gray-50 p-3 rounded-lg">
          <div class="text-gray-600">打印数量</div>
          <van-stepper 
            v-model="quantity" 
            min="1" 
            max="100" 
            button-size="28px"
            input-width="40px"
          />
        </div>

        <div v-if="isPrinting" class="mt-4">
          <van-progress 
            :percentage="printProgress" 
            stroke-width="8"
            color="#1989fa"
            :show-pivot="false"
          />
          <div class="text-center text-gray-500 mt-2">打印中...{{ printProgress }}%</div>
        </div>
      </div>
    </div>

    <div class="border-t bg-white p-3">
      <div class="flex gap-3">
        <van-button 
          type="default" 
          block 
          round 
          @click="showPopup = false"
        >
          关闭
        </van-button>
        
        <van-button 
          type="primary" 
          block 
          round 
          @click="print"
          :loading="isPrinting"
        >
          打印
        </van-button>
      </div>
    </div>
  </van-popup>
</template>
